<template>
  <div>
    <div>
      <DynamicTable row-key="id" header-title="工单督办" show-index :data-request="listWorkOrderNoEnd" :columns="columns"
        bordered size="small">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'workOrderNumber'">
            <a class="workOrderNumber" v-on:click="openMenuModal(record)">{{ record.workOrderNumber }} </a>
          </template>
        </template>
      </DynamicTable>
    </div>
    <div>
      <DraggableModal v-model:visible="processHisvisible" title="流转历史"
        :body-style="{ maxHeight: '50vh', overflowY: 'auto' }" :destroyOnClose="true" :centered=false width="60%"
        :keyboard="false" :fullscreen=false :closable=true footer="">
        <processHistory :process-his-show="processHisShow" :order-info-show="orderInfoShow" :data-object="pageDataObj" :work-order-number="workOrderNumber"  :instance-id="instanceId"></processHistory>
      </DraggableModal>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { baseColumns, pageDataObj, type TableColumnItem } from './columns';
import { uploadFileObject, superviseschemas } from '@/views/workorder/supervise/formSchemas'
import { dictPotionsListApi } from '@/api/workorder/select';
import { listWorkOrderNoEnd } from '@/api/workorder/order';
import { useTable } from '@/components/core/dynamic-table';
import { useFormModal } from '@/hooks/useModal/useFormModal';
import { getCategaryList } from '@/api/workorder/categary';
import { DraggableModal } from '@/components/core/draggable-modal';
import { getDeptList } from '@/api/system/dept';
import { addSupervise, getInitSupervise } from '@/api/workorder/supervise'
import processHistory from '@/views/workorder/task/processHistory/index.vue';
import { ref } from 'vue';
import { string } from 'vue-types';
import { formatCategary2Tree, formatDept2Tree } from '@/core/permission/utils';
import { uploadAttament } from '../common/common';



defineOptions({
  name: 'SystemPermissionWorkOrder',
});

const [DynamicTable, dynamicTableInstance] = useTable({
  formProps: {
    fieldMapToTime: [
      ['acceptTime', ['acceptStartTime', 'acceptEndTime'], 'YYYY-MM-DD HH:mm:ss'],
    ]
  }
});
const [showModal] = useFormModal();
// 流转历史是否显示
const processHisvisible = ref(false);
let instanceId = ref(string);
let workOrderNumber = ref(string);
let modelTitle = ref('');
let processHisShow = ref(false)
let orderInfoShow = ref(false);

// 自定义转码字典
dictPotionsListApi({ "code": 'workorder_type' }).then((res) => {
  pageDataObj.workOrderTypeDict = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
}).then(() => {
  // 改变搜索框数据
  dynamicTableInstance?.getQueryFormRef()?.updateSchema({
    field: `workOrderType`,
    componentProps: {
      options: pageDataObj.workOrderTypeDict,
    },
  });
});
dictPotionsListApi({ "code": 'workorder_status' }).then((res) => {
  pageDataObj.workOrderStatus = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
}).then(() => {
  // 改变搜索框数据
  dynamicTableInstance?.getQueryFormRef()?.updateSchema({
    field: `workOrderStatus`,
    componentProps: {
      options: pageDataObj.workOrderStatus,
    },
  });
});
getCategaryList({ "sysCode": 'workorder',  'visible': '0', 'categaryCode': 'industry_type' }).then((res) => {
  pageDataObj.industryTypeDict = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
  dynamicTableInstance?.getQueryFormRef()?.updateSchema({
    field: `industryType`,
    componentProps: {
      treeData: formatCategary2Tree(res, '0'),
    },
  });
});
getDeptList().then((res) => {
  pageDataObj.responsibleUnitDict = res.map((item) => ({
    label: item.name,
    value: item.id,
  }));
  dynamicTableInstance?.getQueryFormRef()?.updateSchema({
    field: `responsibleUnit`,
    componentProps: {
      treeData: formatDept2Tree(res),
    },
  });
})
dictPotionsListApi({ "code": 'area' }).then((res) => {
  pageDataObj.areaDict = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
})
dictPotionsListApi({ "code": 'region' }).then((res) => {
  pageDataObj.regionDict = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
})
dictPotionsListApi({ "code": 'info_serrces' }).then((res) => {
  pageDataObj.infoSerrcesTypeDict = res.map((item) => ({
    label: item.name,
    value: item.code,
  }));
})

const columns: TableColumnItem[] = [
  ...baseColumns,
  {
    title: '操作',
    width: 120,
    dataIndex: 'ACTION',
    hideInSearch: true,
    align: 'center',
    fixed: 'right',
    actions: ({ record }) => [
      {
        label: '流转历史',
        onClick: () => processHisvisibleModel(record),
      },
      {
        label: '督办',
        onClick: () => openSuperviseModal(record),
      },
    ],
  },
];

/**
 * @description 打开新增回复单填报页面
 */
const openSuperviseModal = async (record) => {
  const [superviseFormRef] = await showModal({
    modalProps: {
      title: `添加督办信息`,
      width: '40%',
      cancelText: '关闭',
      onFinish: async (values) => {
        // 赋值工单编号（感觉id比较合适 ~~~）
        values.workOrderNumber = record.workOrderNumber;
        // 保存回复单信息
        let supervise = await addSupervise(values);
        // 上传附件并保存附件信息
        // 附件上传(回复单)
        await uploadAttament(uploadFileObject.uploadFileList, 'supervise', supervise.id,);
        setTimeout(() => { window.location.reload() }, 1500);
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: superviseschemas,
    },
  });
  // 初始化回复单基本信息
  const data = await getInitSupervise();
  superviseFormRef?.setFieldsValue({
    superviseNo: data.superviseNo,
    filledTime: data.filledTime,
    filledBy: data.filledBy,
  });
};

/**
 * @description 打开新增/编辑弹窗
 */
 async function openMenuModal(record) {
  // 打开操作框选择页面
  let data = record;
  processHisvisible.value = true;
  instanceId = data.instanceId;
  workOrderNumber = data.workOrderNumber;
  modelTitle.value = '工单信息';
  processHisShow.value = false;
  orderInfoShow.value = true;
};

async function processHisvisibleModel(record) {
  // 打开操作框选择页面
  processHisvisible.value = true;
  instanceId = record.instanceId;
  workOrderNumber = record.workOrderNumber;
  modelTitle.value = '流转历史';
  processHisShow.value = true;
  orderInfoShow.value = false;
}
</script>
<style lang="less">
.ant-input-number {
  width: 100%;
}

.workOrderNumber {
  color: #1890ff;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ant-tooltip-inner{
  width: 500px;
}
</style>

